import React, { useState } from 'react'
import { Form, Input, Button, Checkbox, message, Divider, Space } from 'antd'
import { UserOutlined, LockOutlined, WechatOutlined, QqOutlined, GithubOutlined } from '@ant-design/icons'
import { useNavigate, useLocation, Link } from 'react-router-dom'
import { useUserStore } from '@/stores'
import { useBreakpoint } from '@/hooks/useBreakpoint'
import './style.css'

interface LoginForm {
  account: string  // 改为account，可以是邮箱或用户名
  password: string
  remember: boolean
}

const LoginPage: React.FC = () => {
  const navigate = useNavigate()
  const location = useLocation()
  const { login } = useUserStore()
  const [loading, setLoading] = useState(false)
  const breakpoint = useBreakpoint()
  const isMobile = breakpoint === 'mobile'

  const from = location.state?.from?.pathname || '/projects'

  const onFinish = async (values: LoginForm) => {
    setLoading(true)
    try {
      // 使用account字段，它可以是邮箱或用户名
      await login(values.account, values.password, values.remember)

      message.success('登录成功！')

      // 先导航，再预加载（避免阻塞）
      navigate(from, { replace: true })

      // 登录成功后在后台预加载常用页面
      requestIdleCallback(async () => {
        const { preloadAuthenticatedRoutes } = await import('@/utils/route-preloader')
        preloadAuthenticatedRoutes()
      })
    } catch (error) {
      message.error(error instanceof Error ? error.message : '登录失败，请检查用户名和密码')
    } finally {
      setLoading(false)
    }
  }

  return (
    <>
      <h2 className={`font-bold text-center mb-6 ${isMobile ? 'text-2xl' : 'text-3xl'}`}>
        用户登录
      </h2>
      <Form
        name="login"
        initialValues={{ remember: true }}
        onFinish={onFinish}
        layout="vertical"
        size={isMobile ? 'large' : 'middle'}
      >
        <Form.Item
          name="account"
          rules={[
            { required: true, message: '请输入用户名或邮箱！' },
          ]}
        >
          <Input
            prefix={<UserOutlined />}
            placeholder="用户名 / 邮箱"
            autoComplete="username"
            style={{
              fontSize: isMobile ? '16px' : '14px',
              minHeight: isMobile ? '44px' : '32px'
            }}
          />
        </Form.Item>

        <Form.Item
          name="password"
          rules={[{ required: true, message: '请输入密码！' }]}
        >
          <Input.Password
            prefix={<LockOutlined />}
            placeholder="密码"
            autoComplete="current-password"
            style={{
              fontSize: isMobile ? '16px' : '14px',
              minHeight: isMobile ? '44px' : '32px'
            }}
          />
        </Form.Item>

        <Form.Item>
          <div className="flex justify-between items-center">
            <Form.Item name="remember" valuePropName="checked" noStyle>
              <Checkbox style={{ fontSize: isMobile ? '16px' : '14px' }}>
                记住我
              </Checkbox>
            </Form.Item>
            <Link
              to="/auth/forgot-password"
              className={isMobile ? 'text-base' : 'text-sm'}
              style={{
                minHeight: isMobile ? '44px' : 'auto',
                lineHeight: isMobile ? '44px' : 'normal',
                display: 'inline-block'
              }}
            >
              忘记密码？
            </Link>
          </div>
        </Form.Item>

        <Form.Item>
          <Button
            type="primary"
            htmlType="submit"
            loading={loading}
            className="w-full"
            style={{ minHeight: isMobile ? '44px' : '32px' }}
          >
            登录
          </Button>
        </Form.Item>

        <div className="text-center" style={{ fontSize: isMobile ? '16px' : '14px' }}>
          还没有账号？ <Link to="/auth/register">立即注册</Link>
        </div>
      </Form>

      {isMobile && (
        <>
          <Divider className="my-4">或</Divider>

          <div className="social-login space-y-2">
            <Button
              icon={<WechatOutlined />}
              size="large"
              className="w-full hover:opacity-90"
              style={{
                backgroundColor: '#07C160',
                color: 'white',
                border: 'none',
                minHeight: '44px'
              }}
              onClick={() => message.info('微信登录功能开发中')}
            >
              微信登录
            </Button>
            <Button
              icon={<QqOutlined />}
              size="large"
              className="w-full hover:opacity-90"
              style={{
                backgroundColor: '#12B7F5',
                color: 'white',
                border: 'none',
                minHeight: '44px'
              }}
              onClick={() => message.info('QQ登录功能开发中')}
            >
              QQ登录
            </Button>
          </div>
        </>
      )}
    </>
  )
}

export default LoginPage